package com.shjn.squirrel.fragment;

import android.graphics.Color;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;

import com.google.gson.Gson;
import com.shjn.squirrel.R;
import com.shjn.squirrel.bean.httpBean.AccountReq;
import com.shjn.squirrel.bean.httpBean.RespCommonResult;
import com.shjn.squirrel.customView.BackAndTimerView;
import com.shjn.squirrel.model.Constant;
import com.shjn.squirrel.model.RecyclerInfoCache;
import com.shjn.squirrel.utils.OkhttpHelper;

import java.io.IOException;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;

/**
 * 回收员打开箱门
 */
public class RecyclerOpenFragment extends BaseFragment implements View.OnClickListener {

    private static RecyclerOpenFragment instance;
    private TextView mCategory;
    private TextView mFullState;
    private TextView mQuantity;
    private TextView mPrice;
    private Button mRecyclerFinished;
    private TextView mOpenTip;
    private TextView mBalance;

    public RecyclerOpenFragment() {
    }

    public synchronized static RecyclerOpenFragment getInstance() {
        if (instance == null) {
            instance = new RecyclerOpenFragment();
        }
        return instance;
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        return createView(inflater, R.layout.recycler_open_door, container);
    }

    @Override
    public void onViewCreated(View view, Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        initTimer();
        initView();
        openBox();
    }

    /**
     * 初始化倒计时器
     */
    private void initTimer() {
        mActivity.mBackAndTimer.setOnBackListener(null).setBackVisibleState(false)
                .setOnTimerFinishListener(new BackAndTimerView.OnTimerFinishListener() {
                    @Override
                    public void onTimerFinish() {
                        //跳转到回收员关闭箱门页面
                        if (!RecyclerCloseFragment.getInstance().isAdded()) {
                            mActivity.getFragmentManager().beginTransaction()
                                    .replace(R.id.mid, RecyclerCloseFragment.getInstance())
                                    .commit();
                        }
                    }
                }).setTime(60).setVisibleState(true).start();
    }

    /**
     * 初始化相关控件
     */
    private void initView() {
        mRecyclerFinished = (Button) mView.findViewById(R.id.btn_recycler_finished);
        mRecyclerFinished.setOnClickListener(this);
        mCategory = (TextView) mView.findViewById(R.id.tv_category);
        mFullState = (TextView) mView.findViewById(R.id.tv_full_value);
        mQuantity = (TextView) mView.findViewById(R.id.tv_garbage_value);
        mPrice = (TextView) mView.findViewById(R.id.tv_price_value);
        mOpenTip = (TextView) mView.findViewById(R.id.tv_open_tip);
        mBalance = (TextView) mView.findViewById(R.id.tv_balance);

        mCategory.setText(RecyclerInfoCache.garbageParam.getCategory() + "回收物");
        mFullState.setText(RecyclerInfoCache.garbageParam.getFullState());
        if (RecyclerInfoCache.garbageParam.getFullState().equals(Constant.full)) {
            mFullState.setTextColor(Color.parseColor("#f6546c"));
        } else {
            mFullState.setTextColor(Color.parseColor("#333333"));
        }
        if (RecyclerInfoCache.garbageParam.getCategory().equals(Constant.bottle)) {
            mQuantity.setText(String.format("%.0f", RecyclerInfoCache.garbageParam.getQuantity()) + "个");
        } else {
            mQuantity.setText(String.format("%.2f", RecyclerInfoCache.garbageParam.getQuantity()) + "公斤");
        }
        mPrice.setText(String.format("%.2f", RecyclerInfoCache.garbageParam.getMoney()) + "元");

        //----------测试用-------------//
        //查询回收员当前余额
//        OkhttpHelper.postRequest(Constant.baseUrl + "machine/recycling/getRecyclingBalance",
//                new Gson().toJson(new AccountReq(RecyclerInfoCache.telNum)),
//                new Callback() {
//                    @Override
//                    public void onFailure(Call call, IOException e) {
//                        Log.i("info", "getRecyclingBalance_onFailure: " + e.getMessage());
//                    }
//
//                    @Override
//                    public void onResponse(Call call, Response response) throws IOException {
//                        RespCommonResult result = new Gson().fromJson(response.body().string(), RespCommonResult.class);
//                        if (result.getStateCode() == 1) {
//                            RecyclerInfoCache.balance = (double) result.getResult().get("balance");
//                            mActivity.runOnUiThread(new Runnable() {
//                                @Override
//                                public void run() {
//                                    if (RecyclerOpenFragment.getInstance().isAdded()) {
                                        mBalance.setText(String.format("%.2f", RecyclerInfoCache.balance) + "元");
//                                    }
//                                }
//                            });
//                        }
//                    }
//                });
    }

    /**
     * 正在打开箱门
     */
    private void openBox() {
        //设置箱门正在打开状态
        mOpenTip.setText("小松鼠正在努力开箱…");
        mRecyclerFinished.setEnabled(false);
        mRecyclerFinished.setText("正在开箱");
        mRecyclerFinished.setTextColor(Color.parseColor("#999999"));
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                mActivity.runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        //设置箱门已打开状态
                        mOpenTip.setText("箱门已开请进行回收");
                        mRecyclerFinished.setEnabled(true);
                        mRecyclerFinished.setText("回收完成");
                        mRecyclerFinished.setTextColor(Color.parseColor("#FFFFFF"));
                    }
                });
            }
        }).start();
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.btn_recycler_finished:
                if (!RecyclerCloseFragment.getInstance().isAdded()) {
                    //暂停倒计时器
                    mActivity.mBackAndTimer.stop();
                    //跳转到回收员取货完成，关闭箱门页面
                    mActivity.getFragmentManager().beginTransaction()
                            .replace(R.id.mid, RecyclerCloseFragment.getInstance())
                            .commit();
                }
                break;
            default:
                break;
        }
    }
}
